import { useEffect, useState } from 'react';
import styles from './home.less';
import ProductCard from '../components/product/card'
import CartPop from '../components/cart/cartpop'
import CartSvg from '../assets/svg/cart'

export default function HomePage() {
  const sizeS = ['XS', 'S', 'M', 'ML', 'L', 'XL', 'XXL']
  const [size, setSize] = useState('L')
  const [goodsALL, setGoodsALL] = useState([])
  const [goodsList, setGoodsList] = useState([])
  const [isShowCart, setShowCart] = useState(false)
  const [cartList, setCartList] = useState([])
  const [cartTotal, setCartTotal] = useState({total: 0, installments: 0, price: 0, currencyFormat: '$'})


  const sizeClick = (event) => {
    if (size !== event.target.innerText){
      setSize(event.target.innerText);
      filterGoods(event.target.innerText)
    }
    // else {
    //   setSize('');
    //   filterGoods(null)
    // }
  }

  useEffect(() => {
    console.log('加载衣服信息');
    fetch('./products.json')
      .then((res) => { return res.json(); })
      .then((data) => {
        setGoodsALL(data.products);
        const list = [...data.products]
        filterGoods(size, list);
      })
      .catch((err) => { console.log('@@@err', err) })
  }, [])

  const filterGoods = (size, allList = goodsALL) => {
    if (size) {
      const list = allList.filter((w) => {
        return w.availableSizes.includes(size)
      })
      setGoodsList(list);
    } else {
      const list = [...allList]
      setGoodsList(list);
    }
  }

  const cartClick = (isShowCart) => {
    setShowCart(isShowCart)
  }

  const addClick = (product) => {
    const newProduct = {...product, availableSize: size, keyValue: product.id + size, quantity: 1}
    let list = []
    if (cartList.filter(w => w.keyValue === newProduct.keyValue).length > 0) {
      cartList.forEach(c => {
        if (c.keyValue === newProduct.keyValue){
          list.push({...c, quantity: c.quantity + 1})
        } else {
          list.push(c)
        }
      })
      setCartList([...list])
    } else {
      list = [...cartList, newProduct]
      setCartList(list)
    }
    compute(list)
  }

  const cartOperate = (type, key) => {
      let list = []
      if (type === 'delete'){
        list = cartList.filter(w => w.keyValue !== key)
        setCartList([...list])
      } else {
        cartList.forEach(c => {
          if (c.keyValue === key){
            list.push({...c, quantity: type === 'add' ? c.quantity + 1 : c.quantity - 1})
          } else {
            list.push(c)
          }
        })
        setCartList([...list])
      }
      compute(list)
  }

  const compute = (list) => {
    const obj = {
      total: 0, installments: 100, price: 0, currencyFormat: '$'
    }
    list.forEach(c => {
      obj.currencyFormat = c.currencyFormat
      if (obj.installments > c.installments){
        obj.installments = c.installments
      }
      obj.total = obj.total + (c.price * c.quantity)
    })
    obj.price = (obj.total/obj.installments).toFixed(2)
    setCartTotal(obj)
  }

  return (
    <div className={styles.home}>
      <div className={styles.screen}>
        <h4>Sizes:</h4>
        <div className={styles.sizeUl}>
          {
            sizeS.map(item => {
              return <div key={item} onClick={sizeClick} className={item === size ? styles['isClick'] + ' ' +styles.sizeLi: styles.sizeLi}>{item}</div>
            })
          }
        </div>
      </div>
      <div>
        <div className={styles.productTig}>{goodsList.length}Product(s) found</div>
        <div>
          {
            goodsList.map(item => {
              return <ProductCard key={item.id} {...item} addClick={addClick}/>
            })
          }
        </div>
      </div>
      {
        isShowCart ? (<CartPop cartClick={cartClick} cartList={cartList} cartOperate={cartOperate} {...cartTotal}></CartPop>) :
        (<div className={styles.cartClose} onClick={() => cartClick(true)}>
          <CartSvg />
          <div className={styles.cartCloseIndex}>{cartList.length}</div>
        </div>)
      }
      {/* {
        isShowDetail ? (<CartPop cartClick={cartClick}></CartPop>) : <></>
      } */}
    </div>
  );
}
